/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  MaintenanceTaskDetailActivity.java   
 * @Package com.jiyi.activity.new_maintenance   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-8-29 下午5:05:54   
 * @version V1.0     
 */  
package com.jiyi.activity.new_maintenance;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.jiyi.adapter.DetectAdapter;
import com.jiyi.bean.maintenance.DetectCate;
import com.jiyi.bean.maintenance.Task;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.inteface.WebApi;
import com.jiyi.widget.picshow.ImagePagerActivity;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.DeviceUtil;
import com.swift.utils.GlideUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**   
 * @ClassName:  MaintenanceTaskDetailActivity   
 * @Description:TODO(维修检测任务详情)   
 * @author: HYM  
 * @date:   2017-8-29 下午5:05:54   
 *      
 */
public class MaintenanceTaskDetailActivity extends ActivityBase {

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;
	
	@BindView(R.id.tvCompany)
	TextView tvCompany;
	@BindView(R.id.tvDate)
	TextView tvDate;
	@BindView(R.id.tvFinishDate)
	TextView tvFinishDate;
	@BindView(R.id.tvUserName)
	TextView tvUserName;
	@BindView(R.id.ivLogo)
	ImageView ivLogo;
	@BindView(R.id.tvJoinMember)
	TextView tvJoinMember;
	@BindView(R.id.tvRemark)
	TextView tvRemark;
	@BindView(R.id.tvInfo)
	TextView tvInfo;
	
	@BindView(R.id.gvDetectItem)
	GridView gvDetectItem;
	
	String id;
	Task task;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_maintenance_task_detail);
		ButterKnife.bind(this);
		init();
	}

	private void init() {
		getIntentData();
		setTop();
		getData();
	}
	
	/**   
	 * @author: HYM 
	 * @Title: getIntentData   
	 * @Description: TODO(这里用一句话描述这个方法的作用)    void 
	 * @date: 2017-9-11
	 */  
	private void getIntentData() {
		id = getIntent().getStringExtra("id");
	}

	private void getData() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", id);

		VolleyRequest.StringRequestPost(this,
				WebApi.MAINTENANCE_DETAIL_TASK, "", params, new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								task = new Gson().fromJson(data, Task.class);
								setInfo(task);
							} 
							else if (status.equals("404") && info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
								//清除环信登录
								UserHelp.getInstance().clearUser(AppBase.Context, true);
								return;
							}
							else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});
		
	}

	private void setTop() {
		tvTitle.setText("维保任务详情");
		tvSearch.setVisibility(View.GONE);
	}
	
	@OnClick({ R.id.tvBack,R.id.tvJoinMember,R.id.ivLogo})
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		case R.id.tvJoinMember:
			Intent intent = new Intent(this,JoinMemberReadActivity.class);
			intent.putExtra("memberList", new Gson().toJson(task.getPartMembers()));
			startActivity(intent);
			break;
		case R.id.ivLogo:
			if (TextUtils.isEmpty(task.getSignImage())) {
				ToastUtil.getInstances().showMsg("无法找到该图片~");
				return;
			}
			final String [] urls = new String [1];
			urls[0] = task.getSignImage();
			intent = new Intent(this,ImagePagerActivity.class);
			intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls);
			intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, 0);
			startActivity(intent);
			break;
		default:
			break;
		}
	}
	
	void setInfo(final Task task)
	{
		tvCompany.setText(task.getTask_name());
		tvDate.setText(task.getTask_time());
		tvFinishDate.setText(task.getFinish_time());
		tvUserName.setText(task.getUser_name());
		GlideUtil.load(this, task.getSignImage(), ivLogo);
		tvRemark.setText(task.getRemark());
		tvInfo.setText(task.getParticipants());
		DetectAdapter mDetectAdapter = new DetectAdapter(this, task.getPrimaryCate());
		gvDetectItem.setAdapter(mDetectAdapter);
		gvDetectItem.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO 跳转到具体的检测系统
				DetectCate detectCate = task.getPrimaryCate().get(position);
				Intent intent = new Intent(parent.getContext(),DetectSystemReadActivity.class);
				intent.putExtra("title", detectCate.getName());
				intent.putExtra("id", detectCate.getTask_inspection_id());
				intent.putExtra("code", detectCate.getCode());
				parent.getContext().startActivity(intent);
			}
		});
		setDetectGridViewHeight(gvDetectItem);
	}
	
	/**   
     * @author: HYM 
     * @Title: setDetectGridViewHeight   
     * @Description: TODO(设置待检测的项目内容高度)   
     * @param gridview void 
     * @date: 2017-8-29
     */  
    public void setDetectGridViewHeight(GridView gridview) {  
        // 获取gridview的adapter  
        ListAdapter listAdapter = gridview.getAdapter();  
        if (listAdapter == null) {  
            return;  
        }  
        // 固定列宽，有多少列  
        int numColumns= 3; 
        int totalHeight = 0;  
        // 计算每一列的高度之和 
        for (int i = 0; i < listAdapter.getCount(); i += numColumns) {  
            // 获取gridview的每一个item  
            View listItem = listAdapter.getView(i, null, gridview); 
            listItem.measure(0, 0);  
            // 获取item的高度和  加上verticalSpacing的距离
            totalHeight += listItem.getMeasuredHeight()+DeviceUtil.dip2px(gridview.getContext(), 20);  
        }   
        
        //判断是否超过我们希望的高度，如果是就强制设置其高度为固定
        if (totalHeight > DeviceUtil.dip2px(gridview.getContext(), 250)) {
        	totalHeight = DeviceUtil.dip2px(gridview.getContext(), 250);
		}
        
        // 获取gridview的布局参数  
        ViewGroup.LayoutParams params = gridview.getLayoutParams();  
        params.height = totalHeight;  
        gridview.setLayoutParams(params);  
    }
}
